package com.chinanet.utils.webservice;

import org.apache.commons.lang.StringEscapeUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HSSWebService extends IWebService {

    /**
     * Init WebService method
     *
     * @param attrsIn
     * @return
     */
    public String WebServiceInit(AttrsIn attrsIn) {
        System.out.println("========>>>");
        String returnBack = "";
        try {
            //地址
            URL url = new URL(
                    "http://134.96.211.133:3001");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("soapAction", "");
            conn.connect();
            String soap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                    "   <SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                                          "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"" +
                                          "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
                                          "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
                                          "xmlns:ns1=\"http://ispp.com.cn/ispp_npi/\" >" +
                    "<SOAP-ENV:Header>" +
                      "<ns1:Username>super</ns1:Username>" +
                      "<ns1:Password>Zte@2013</ns1:Password>" +
                      "<ns1:MessageID>20074818</ns1:MessageID>" +
                      "<ns1:Address>HssAddr</ns1:Address>" +
                      "<ns1:VHLRID></ns1:VHLRID>" +
                      "<ns1:HLRNUMBER></ns1:HLRNUMBER>" +
                      "<ns1:MARKID></ns1:MARKID>" +
                      "<ns1:SWITCHNUM></ns1:SWITCHNUM>" +
                      "<ns1:HLRIN></ns1:HLRIN>" +
                    "</SOAP-ENV:Header>" +
                    "<SOAP-ENV:Body>" +
                      "<ns1:root>" +
                        "<msg_head>" +
                          "<time>2018-05-17 13:07:41</time>" +
                          "<from></from>" +
                          "<to></to>" +
                          "<msg_type></msg_type>" +
                          "<serial>20074818</serial>" +
                        "</msg_head>" +
                        "<interface_msg>" +
                          "<directive>" +
                            "<HSSClass Name=\""+ attrsIn.getClientSysName()+"\">" +
                            "<HSSMethod Name=\""+ attrsIn.getFunctionName()+"\">" +
                               attrsIn.getRequestMessage()+
                            "</HSSMethod>" +
                            "</HSSClass>" +
                           "</directive>" +
                        "</interface_msg>" +
                      "</ns1:root>" +
                    "</SOAP-ENV:Body>" +
                    "</SOAP-ENV:Envelope> ";
            System.out.println("组装的结果:"+soap);
            OutputStream out = conn.getOutputStream();
            out.write(soap.getBytes("GBK"));
            out.flush();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream in = conn.getInputStream();
                byte b[] = new byte[10240];
                StringBuffer sb = new StringBuffer();
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    String str = new String(b, 0, len, "GBK");
                    sb.append(str);
                }
                String ak = new String(sb.toString());
                ak = ak.replaceAll("&amp;", "");
                ak = ak.replaceAll("&lt;", "<");
                ak = ak.replaceAll("&gt;", ">");
                ak = ak.replaceAll("lt;", "<");
                ak = ak.replaceAll("gt;", ">");
                ak = ak.replaceAll("&quot;", "\"");
                ak = ak.replaceAll("&apos;", "\'");
                ak = ak.replaceAll(";", "");
                ak = ak.replaceAll("&#x", "\\\\u");
                returnBack = StringEscapeUtils.unescapeJava(ak);
                in.close();
            } else if (code == 500) {
                System.out.println("server ERROR!");
            } else if (code == 504) {
                System.out.println("Gateway Timeout!");
            } else if (code == 404) {
                System.out.println("Not Found!");
            } else if (code == 408) {
                System.out.println("Request Time-Out!");
            } else {
                System.out.println("Connection Failed!");
            }
            out.close();
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnBack;

    }

    /**
     * Init WebService method
     *
     * @param attrsIn
     * @return
     */
    public String WebServiceInit(AttrsIn attrsIn, Map<String, String> param) {
        System.out.println("========>>>");
        String returnBack = "";
        try {
            //地址
            URL url = new URL(
                    "http://134.96.104.121:8096/eai/services/EAIService");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("soapAction", "");
            StringBuilder sbd = new StringBuilder();
            for (Map.Entry<String, String> e : param.entrySet()) {
                sbd.append("<" + e.getKey() + ">" + e.getValue() + "<" + e.getKey() + ">");
            }
            conn.connect();
            String soap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:bus=\"http://businessmanager.eai.zjpii.com\">"
                    + "<soapenv:Header/>"
                    + "<soapenv:Body>"
                    + "<HSSClass Name=\"" + attrsIn.getClientSysName() + "\">"
                    + "<HSSMethod Name=\"" + attrsIn.getFunctionName() + "\">"
                    + sbd.toString()
                    + "</HSSMethod>"
                    + "</HSSClass>"
                    + "</soapenv:Body>"
                    + "</soapenv:Envelope>";
            OutputStream out = conn.getOutputStream();
            out.write(soap.getBytes("UTF-8"));
            out.flush();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream in = conn.getInputStream();
                byte b[] = new byte[10240];
                StringBuffer sb = new StringBuffer();
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    String str = new String(b, 0, len, "UTF-8");
                    sb.append(str);
                }
                String ak = new String(sb.toString());
                ak = ak.replaceAll("&amp;", "");
                ak = ak.replaceAll("&lt;", "<");
                ak = ak.replaceAll("&gt;", ">");
                ak = ak.replaceAll("lt;", "<");
                ak = ak.replaceAll("gt;", ">");
                ak = ak.replaceAll("&quot;", "\"");
                ak = ak.replaceAll("&apos;", "\'");
                ak = ak.replaceAll(";", "");
                ak = ak.replaceAll("&#x", "\\\\u");
                returnBack = StringEscapeUtils.unescapeJava(ak);
                in.close();
            } else if (code == 500) {
                System.out.println("server ERROR!");
            } else if (code == 504) {
                System.out.println("Gateway Timeout!");
            } else if (code == 404) {
                System.out.println("Not Found!");
            } else if (code == 408) {
                System.out.println("Request Time-Out!");
            } else {
                System.out.println("Connection Failed!");
            }
            out.close();
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnBack;

    }

    /**
     * The content of the find nodes
     *
     * @param nodeName
     * @param xml
     * @return
     */
    public String getPattern(String nodeName, String xml) {
        String returnBack = "";
        String regex = "<" + nodeName + ">([\\s\\S].*)</" + nodeName + ">";
        xml = xml.replaceAll("\\r", "");
        xml = xml.replaceAll("\\n", "");
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(xml);
        while (matcher.find()) {
            returnBack = matcher.group(1);
        }
        return dealkouhao(returnBack);
    }

    public String dealkouhao(String returnXml) {
        returnXml = returnXml.replaceAll("\"", "\'");
        if (returnXml.equals("null")) {
            returnXml = "没有数据";
        }
        return returnXml;
    }


    public static String getrandom() {
        return new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + String.valueOf(generateRandomNumber(3));
    }

    public static String timeget(int i) {
        if (i == 0) {
            return new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(new Date());
        } else {
            Calendar curr = Calendar.getInstance();
            curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) - 7);
            Date date = curr.getTime();
            return new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(date);
        }
    }

    private static long generateRandomNumber(int n) {
        if (n < 1) {
            throw new IllegalArgumentException("随机数位数必须大于0");
        }
        return (long) (Math.random() * 9 * Math.pow(10, n - 1)) + (long) Math.pow(10, n - 1);
    }
//
//	public static void main(String[] args){
//		System.out.println(timeget(0));
//	}

    public static void main(String args[]){

    }
}
